# coding=utf-8
from abc import ABCMeta
import tornado.web
import tornado.escape
import json

from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.Normal import Normal
from database.models.OperationSet import OperationSet
import WrapCursor
from database.models.PanelInstruct import PanelInstruct


class UptPanelNormal(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        ojson = None
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            CheckJsonKeys(ojson, 'ControllerID', 'key', 'normalID')
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error(u'请求数据错误 :' + str(e.message)))
            return
        cid = ojson['ControllerID']
        nid = ojson['normalID']
        key = ojson['key']

        s = Session()
        nc = s.query(PanelInstruct).filter_by(ControllerID=cid, Key=key).all()

        if nc is None or len(nc) == 0:
            self.write(r.Error(u'按键动作不存在'))
            return
        # 可能更新不了，采用使用session进行更新的办法 s.query.filter.update
        nc[0].NormalID = nid

        try:
            s.commit()
        except Exception as e:
            self.write(r.Error(str(u'失败:更新按键动作失败')))
            return
        self.write(r.Ok(u'成功'))
        return
